<?php
	/**
	 * 
	 * Offer operations on the admin table when the user is not "ADMIN"
	 *
	 */
	class User extends Model_Abstract{
		
		private $_cons = '';
		private $_vars = array();
		private $_limit = 10;
		
		public function getUserByField( $field, $fieldVal ){
			try
			{
				$sql = " SELECT * FROM users WHERE {$field}=? AND filtered=0 ";
				$result = $this->_connection->query($sql, array($fieldVal));
				if(!empty($result))	
					return $result[0];
				return false;
			}
			catch (Exception $e)
			{
				QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
				throw new Model_Exception($e->getMessage(), $e->getCode());
			}
		}
				
		public function getCount(){
			try
			{
				$sql = "select count(*) as total from users as u where";
				if(!count($this->_cons)){
					$pos = strpos($sql, 'where');
					$sql =  substr($sql, 0, $pos-1);
				}elseif (count($this->_cons)>1){
					$cons = implode(' and', $this->_cons);
				}
				$result = $this->_connection->query($sql . $this->_cons, $this->_vars);
				if($result)
					return $result[0]['total'];
				return false;
			}
			catch (Exception $e)
			{
				QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
				throw new Model_Exception($e->getMessage(), $e->getCode());
			}
		}
		
		public function search($field, $condition, $page){
			$sql = "select u.id as id, s.domain as domain, u.firstname, u.lastname, u.state, u.won
							, u.balance, u.unsub, u.last_visit from users as u left join sites as s on u.site_id=s.id where";
			$cons = '';
			if('id' == $field){
				$cons .= " u.id=?";
			}elseif('email' == $field)
			{
				$cons .= " u.email=?";
			}else{
				if ('email' == $field)
					$cons .= " u.email like ?";
				elseif ('firstname' == $field)
					$cons .= " u.firstname like ?";
				else 
					$cons .= " u.lastname like ?";
				$condition = "%" . trim($condition) . "%";
			}
			$limit = is_null(Q::ini('appini/items_per_page')) ?  $this->_limit : Q::ini('appini/items_per_page');
			$constraint = " limit " .($page-1)*$limit . ", $limit";
			$this->_cons = $cons;
			$vars = array($condition);
			$this->_vars = $vars;
			
			try
			{
				$result = $this->_connection->query($sql . $cons . $constraint, $vars);
				return $result;
			}
			catch (Exception $e)
			{
				QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
				throw new Model_Exception($e->getMessage(), $e->getCode());
			}
			
		}
		
		public function advancedSearch($state, $gender, $site, $cre_from, $cre_to, $won_from, $won_to
								, $balance_from, $balance_to, $created_from, $created_to, $lvisit_from, $lvisit_to, $unsub, $page=1)
		{	
			$vars = array();
			$sql = "select u.id, s.domain, u.firstname, u.lastname, u.state, u.won
							, u.balance, u.last_visit from users as u left join sites as s on u.site_id=s.id where";		
			
			if(!empty($state)){
				$cons[] = ' state=?';
				$vars[] = $state;
			}
			
			if(!empty($gender)){
				$cons[] = ' gender=?';
				$vars[] = $gender;
			}
			
			if(!empty($site)){
				$cons[] = ' site_id=?';
				$vars[] = $site;
			}
			
			if(!empty($cre_from) && !empty($cre_to)){
				$cons[] = ' credit between ? and ?';
				$vars[] = $cre_from;
				$vars[] = $cre_to;
			}elseif (!empty($cre_from)){
				$cons[] = ' credit > ?';
				$vars[] = $cre_from;
			}elseif (!empty($cre_to)){
				$cons[] = ' credit < ?';
				$vars[] = $cre_to;
			}
			
			if(!empty($won_from) && !empty($won_to)){
				$cons[] = ' won between ? and ?';
				$vars[] = $won_from;
				$vars[] = $won_to;
			}elseif (!empty($won_from)){
				$cons[] = ' won > ?';
				$vars[] = $won_to;
			}elseif (!empty($cre_to)){
				$cons[] = ' won < ?';
				$vars[] = $won_to;
			}
			
			if(!empty($balance_from) && !empty($balance_to)){
				$cons[] = '  balance between ? and ?';
				$vars[] = $balance_from;
				$vars[] = $balance_to;
			}elseif (!empty($balance_from)){
				$cons[] = '  balance > ?';
				$vars[] = $balance_from;
			}elseif (!empty($balance_to)){
				$cons[] = ' balance < ?';
				$vars[] = $balance_to;
			}			
		
			if(!empty($created_from) && !empty($created_from)){
				$cons[] = '  created between ? and ?';
				$vars[] = strtotime($created_from);
				$vars[] = strtotime($created_from);
			}elseif (!empty($created_from)){
				$cons[] = '  created > ?';
				$vars[] = strtotime($created_from);
			}elseif (!empty($created_from)){
				$cons[] = ' created < ?';
				$vars[] = strtotime($created_from);
			}
			
			if(!empty($lvisit_from) && !empty($lvisit_to)){
				$cons[] = '  last_visit between ? and ?';
				$vars[] = strtotime($lvisit_from);
				$vars[] = strtotime($lvisit_to);
			}elseif (!empty($lvisit_from)){
				$cons[] = '  last_visit > ?';
				$vars[] = strtotime($lvisit_from);
			}elseif (!empty($lvisit_to)){
				$cons[] = ' last_visit < ?';
				$vars[] = strtotime($lvisit_to);
			}

			if(null !== $unsub){
				$cons[] = '  unsub=?';
				$vars[] = $unsub;
			}			
			
			//when there's extra condition, remove the 'where' clauses or join all conditons together
			if(!count($cons)){
				$pos = strpos($sql, 'where');
				$sql =  substr($sql, 0, $pos-1);
			}else{
				$cons = implode(' and', $cons);
			}
			
			$this->_cons = $cons;
			$this->_vars = $vars;
			
			$limit = is_null(Q::ini('appini/items_per_page')) ?  $this->_limit : Q::ini('appini/items_per_page');
			$constraint = " limit " .($page-1)*$limit . ", $limit";
			
			
			try
			{
				$result = $this->_connection->query($sql . $cons . $constraint, $vars);
				return $result;
			}
			catch (Exception $e)
			{
				QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
				throw new Model_Exception($e->getMessage(), $e->getCode());
			}
		}
		
		public function cancelFulfillment($uid, $amount){
			$sql = "update users set balance=balance+? where id=?";
			try
			{
				$result =  $this->_connection->execute($sql, array($amount, $uid));
				return $result;
			}
			catch (Exception $e)
			{
				QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
				throw new Model_Exception($e->getMessage(), $e->getCode());
			}
		}
		
		public function reverseUnsub($userid, $unSub_val){
			$sql = "UPDATE `users` SET unsub=? WHERE id=? ";
			try
			{
				$result = $this->_connection->execute($sql, array($unSub_val, $userid));
				return $result;
			}
			catch (Exception $e)
			{
				QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
				throw new Model_Exception($e->getMessage(), $e->getCode());
			}
		}
		
		public function setPassword($userid, $password){
			$sql = "UPDATE `users` SET password=? WHERE id=? ";
			try
			{
				$result = $this->_connection->execute($sql, array($password, $userid));
				return $result;
			}
			catch (Exception $e)
			{
				QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
				throw new Model_Exception($e->getMessage(), $e->getCode());
			}
		}
		
		public function rewardCredits($userid, $credits){
			$sql = "UPDATE `users` SET credit=credit+? WHERE id=? ";
			try
			{
				if($this->_connection->execute($sql, array($credits, $userid))){
					$offerModel = new Reward();
					return $offerModel->addRewardByMonetization($userid, 'Customer Service', $credits);
				}
				return false;
			}
			catch (Exception $e)
			{
				QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
				throw new Model_Exception($e->getMessage(), $e->getCode());
			}
		}
		
		public function getSitetokeninfo($site_id){
			$sql = "select user_id,  sum(rewards.credit) as tokens from rewards left join users on users.id=rewards.user_id where users.site_id=? group by user_id order by tokens desc; ";
			try
			{
				$result = $this->_connection->query($sql, array($site_id));
				return $result;
			}
			catch (Exception $e)
			{
				QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
				throw new Model_Exception($e->getMessage(), $e->getCode());
			}
		}
		
		public function getSitedailytokeninfo($site_id){
			$sql = "SELECT user_id, rewards.credit AS token, users.created AS uc, rewards.created AS rc FROM rewards LEFT JOIN users ON users.id = rewards.user_id WHERE users.site_id =?";
			try
			{
				$result = $this->_connection->query($sql, array($site_id));
				return $result;
			}
			catch (Exception $e)
			{
				QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
				throw new Model_Exception($e->getMessage(), $e->getCode());
			}
		}
		
		public function getEmailsByIds($usersId)
		{
			$sql = " SELECT email FROM users WHERE id IN ( " . implode(', ', $usersId) . " ) ";
			try{
				$result = $this->_connection->query($sql);
				return $result;
			}catch (Exception $e){
				QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
				throw new Model_Exception($e->getMessage(), $e->getCode());
			}
		}
		
		public function forgetPassword($email, $site_id)
		{
			$sql = 'update users set password=? where email=? and site_id=? and unsub=0';
			$password = Util::getRandonPassword();
			try{
				$result =  $this->_connection->execute($sql, array($password[1], $email, $site_id));
				if($result)
					return $password[0];
				return false;
			}catch (Exception $e){
				QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
				throw new Model_Exception($e->getMessage(), $e->getCode());
			}
		}
		
		public function updateToken($uid)
		{
			$token = Util::generateToken();
			try
			{
				$sql = " UPDATE users SET token=? WHERE id=? ";
				$result = $this->_connection->execute($sql, array($token, $uid));
				if($result)
					return $token;
				return false;
			}
			catch (Exception $e)
			{
				QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
				throw new Model_Exception($e->getMessage(), $e->getCode());
			}
		}
		
		/**
		 * update users unsub=1
		 * @author mason
		 * @since 2012-5-9
		 * @param $uid
		 * @return int
		 */
		public function updateUnsub($uid)
		{
			$sql = 'update users set unsub=1 where id=? ';
			try{
				$result =  $this->_connection->execute($sql, array($uid));
				if($result > 0)
					return true;
				return false;
			}catch (Exception $e){
				QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
				throw new Model_Exception($e->getMessage(), $e->getCode());
			}
		}
	}